package com.zhz.lib.cms.security.userinfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.map.ListOrderedMap;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;

public class UserInfoBuilderImplWithJdbc implements UserInfoBuilder {
	private JdbcTemplate jdbcTemplate;

	private String authorityUrl = "SELECT ga.authority "
			+ "FROM groups g, group_members gm, group_authorities ga "
			+ "WHERE g.id = ga.group_id AND g.id = gm.group_id and gm.username='";
	private String userInfoUrl = "SELECT * from user u where u.username='";

	@SuppressWarnings("unchecked")
	public Map<String, UserInfo> buildUserInfoMap(String username) {
		Map<String, UserInfo> userMap = new HashMap<String, UserInfo>();

		List<ListOrderedMap> userinfolist = jdbcTemplate
				.queryForList(userInfoUrl + username + "'");

		List<ListOrderedMap> list = jdbcTemplate.queryForList(authorityUrl
				+ username + "'");
		int size = list.size();
		if (null != list)
			if (size > 0) {
				ListOrderedMap u = userinfolist.get(0);
				int status = (Integer) u.get("status");
				boolean enable = status == 1 ? true : false;
				String password = (String) u.get("password");
				Integer id = (Integer) u.get("id");
				String email = (String) u.get("email");
				String name = (String) u.get("name");

				GrantedAuthority[] ga = new GrantedAuthority[list.size()];

				for (int k = 0; k < size; k++) {
					String authority = (String) list.get(k).get("authority");
					ga[k] = new GrantedAuthorityImpl(authority);
				}
				UserInfo ui = new UserInfo(username, password, enable, ga);
				ui.setId(Integer.toString(id));
				ui.setEmail(email);
				ui.setName(name);
				userMap.put(username, ui);
			}

		return userMap;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

}
